<?php

namespace App\Services;

use App\Exceptions\BusinessException;
use App\Models\PhoneCodeModel;
use App\Models\Sms\Sms;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;

class UserService
{
    private $userRepository;

    public static $user;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function userInfo($id)
    {
        return $this->userRepository->getUserById($id);
    }




    public function createUser(Request $request)
    {
        $user = $this->userRepository->getUserByPhone($request->phone);
        if (!empty($user)) {
            throw new BusinessException('phone already exist', 10003);
        }

        $phoneCode = PhoneCodeModel::query()->where('phone', '=', $request->phone)->orderBy('created_at', 'desc')->first();
        if (empty($phoneCode) || $phoneCode->getAttribute('code') != $request->code) {
            throw new BusinessException('验证码错误！', 10004);
        }

        $uid = $this->userRepository->addUser($request->name ?? $request->phone, $request->phone, $request->password);
        //注册成功自动登录返回token
        return $this->userRepository->addUserAccess(
            $uid,
            [
                'uid'=>$uid,
                'name' => $request->name,
                'type' => 0
            ]
        );
    }

    public function login($phone, $password, $code)
    {
        if ($code != 999999) {
            throw new BusinessException('Phone Code error!', 10005);
        }
        $user = $this->userRepository->getUserByPhone($phone);
        if (empty($user)) {
            throw new BusinessException('No account exists', 10002);
        }
        if ($user->password != md5($password)) {
            throw new BusinessException('Password error', 10003);
        }
        $token = $this->userRepository->addUserAccess($user['id'], [
            'uid' => $user['id'],
            'name' => $user['name'],
            'type' => $user['type']
        ]);
        return $token;
    }

    public static function auth(array $user)
    {
        self::$user = $user;
    }

    public function sendRegisterPhoneCode($phone)
    {
        $user = $this->userRepository->getUserById($phone);
        if (!empty($user)) {
            throw new BusinessException('Phone already exists', 10002);
        }
        $phonecodereload = PhoneCodeModel::query()->where('phone' , '=', $phone)->orderBy('created_at', 'desc')->first()->toArray();
        if (!empty($phonecodereload) && $phonecodereload['effective_time'] > time()) {
            throw new BusinessException('请勿重复发送短信', 20001);
        }
        $sms = new Sms();
        $code = rand(100000, 999999);
        $msg = "【美策】验证码{$code}，您正在进行美策平台的账号注册，有效时间30分钟身份验证，打死不要告诉别人哦！";
        $ret = $sms->sendSMS($phone, $msg);
        $ret = json_decode($ret, true);
        //"{"code":"0","msgId":"19030116061125059","time":"20190301160611","errorMsg":""}"
        if (empty($ret) || !empty($ret['errorMsg'])) {
            throw new BusinessException('验证码发送失败!', 2003);
        }
        $phoneCode = new PhoneCodeModel();
        $phoneCode->setRawAttributes([
            'phone' => $phone,
            'code' => $code,
            'effective_time' => time() + 1800,
            'created_at' => time()
        ])->save();
    }

}
